<template>
  <div>
    <div class="top-step">
      <div class="v-align-c">
        <div class="step-index" :class="{'step-active': activeIndex === 1}">1</div>
        <div class="mar-l-7 font-14">提货点位置</div>
      </div>
      <span class="mar-l-5 mar-r-5 mar-t--8 B5">...</span>
      <div class="v-align-c">
        <div class="step-index" :class="{'step-active': activeIndex === 2}">2</div>
        <div class="mar-l-7 font-14">提货点信息</div>
      </div>
      <template v-if="!storeApply">
        <span class="mar-l-5 mar-r-5 mar-t--8 B5">...</span>
        <div class="v-align-c">
          <div class="step-index" :class="{'step-active': activeIndex === 3}">3</div>
          <div class="mar-l-7 font-14">个人信息</div>
        </div>
      </template>
    </div>
    <step-one ref="stepOne" :activeIndex="activeIndex" v-if="activeIndex === 1" @change="stepOneChange"></step-one>
    <step-two ref="stepTwo" :activeIndex="activeIndex" v-if="activeIndex === 2" @change="stepTwoChange"></step-two>
    <step-three ref="stepThree" :activeIndex="activeIndex" v-if="activeIndex === 3 && !storeApply" @change="stepThreeChange"></step-three>
    <div class="height-64"></div>
    <div class="footer">
      <div class="last-step" v-show="activeIndex !== 1" @click="lastStep">上一步</div>
      <div class="next-step" @click="nextStep">下一步</div>
    </div>
    <div class="div-pop" v-if="showConfirm" catchtouchmove="ture">
      <div class="tip-box">
        <div class="tip-box--title">确认提货点信息</div>
        <div class="tip-box--content">
          <div class="flex">
            <span class="font-color-6">名称</span>
            <span class="mar-l-9 flex-item">{{params.takeName}}</span>
          </div>
          <div class="flex">
            <span class="font-color-6">地址</span>
            <span class="mar-l-9 flex-item">{{params.address.address + params.address.name}}</span>
          </div>
        </div>
        <div class="tip-box--footer">
          <div class="tip-box__cancel" @click="cancelNextStep">重新修改</div>
          <div class="tip-box__confirm" @click="confirmNextStep">下一步</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import StepOne from './component/step-one'
import StepTwo from './component/step-two'
import StepThree from './component/step-three'
import { saveVillageCommanderApply } from '@/api/home'
export default {
  components: { StepOne, StepTwo, StepThree },
  data() {
    return {
      phone: '',
      memberId: '',
      activeIndex: 1,
      showConfirm: false,
      params: {},
      uploadImgs: [], // 准备上传的文件数组
      uploadedImgs: {}, // 上传成功的文件对象
      uploadTotalCount: 0,
      uploadedCount: 0,
      uploadErrCount: 0, // 单张图片上次出错次数
      storeApply: false,
      appInfo: {}
    }
  },
  mounted() {
    this.storeApply = this.$pt.getStorageSync('store-apply') // 获取门店申请缓存，判断是申请门店还是申请团长
    if (this.storeApply) {
      this.$pt.setNavigationBarTitle({
        title: '申请门店'
      })
    } else {
      this.$pt.setNavigationBarTitle({
        title: '申请成为团长'
      })
    }
    let applyStore = this.$pt.getStorageSync('applyStore') // 获取各个步骤缓存的申请的内容
    this.appInfo = this.$pt.getStorageSync('appInfo')
    this.phone = this.getCurrentPage().query.phone || this.$pt.getStorageSync('temporaryPhone')
    this.memberId = this.getCurrentPage().query.memberId || this.$pt.getStorageSync('temporaryMemberId')
    this.params = applyStore || {}
  },
  methods: {
    lastStep() {
      // 上一步
      this.$pt.setStorageSync('applyStore', this.params)
      this.activeIndex--
    },
    nextStep() {
      // 下一步
      if (this.activeIndex <= 3) {
        let result = false
        switch (this.activeIndex) {
          case 1:
            // 取到组件中检查页面数据是否正确填写，正确填写返回true  否则返回false
            result = this.$refs.stepOne.checkData()
            if (result) {
              this.showConfirm = true
            }
            break
          case 2:
            // 取到组件中检查页面数据是否正确填写，正确填写返回true  否则返回false
            result = this.$refs.stepTwo.checkData()
            if (result) {
              this.$pt.setStorageSync('applyStore', this.params)
              if (this.storeApply) {
                // 调用保存接口
                this.saveData()
              } else {
                this.activeIndex++
              }
            }
            break
          case 3:
            // 取到组件中检查页面数据是否正确填写，正确填写返回true  否则返回false
            result = this.$refs.stepThree.checkData()
            // 最后一步，正确了就提交数据 跳转页面
            console.log('result', result)
            if (result) {
              this.$pt.setStorageSync('applyStore', this.params)
              // 调用保存接口
              console.log(11111)
              this.saveData()
            }
            break
          default:
            break
        }
      }
    },
    stepOneChange(e) {
      // 第一步组件里面的数据变更
      console.log('数据1变更', e)
      this.$set(this.params, 'isHasStore', e.isHasStore)
      this.$set(this.params, 'takeName', e.takeName)
      this.$set(this.params, 'address', e.address)
    },
    stepTwoChange(e) {
      // 第二步组件里面的数据变更
      console.log('数据2变更', e)
      this.$set(this.params, 'takeTypeId', e.takeTypeId)
      this.$set(this.params, 'pickupName', e.pickupName)
      this.$set(this.params, 'pickupIndex', e.pickupIndex)
      this.$set(this.params, 'businessLicensePicUrl', e.businessLicensePicUrl)
      this.$set(this.params, 'takeAddressPicUrl', e.takeAddressPicUrl)
      this.$set(this.params, 'quartersSrc', e.quartersSrc)
    },
    stepThreeChange(e) {
      // 第三步组件里面的数据变更
      console.log('数据3变更', e)
      this.$set(this.params, 'idCardPortraitPhotoUrl', e.idCardPortraitPhotoUrl)
      this.$set(this.params, 'idCardNationalEmblemPicUrl', e.idCardNationalEmblemPicUrl)
      this.$set(this.params, 'idCardRealName', e.idCardRealName)
      this.$set(this.params, 'idCardNumber', e.idCardNumber)
    },
    confirmNextStep() {
      // 下一步
      this.$pt.setStorageSync('applyStore', this.params)
      this.activeIndex++
      this.showConfirm = false
    },
    cancelNextStep() {
      // 重新修改
      this.showConfirm = false
    },
    saveData() {
      // 保存数据方法
      // 先处理图片上传
      let uploadImgs = [{
        name: '营业执照',
        key: 'businessLicensePicUrl',
        src: this.params.isHasStore === 1 ? this.params.businessLicensePicUrl : ''
      }, {
        name: this.params.isHasStore === 1 ? '门店照片' : '小区照片',
        key: 'takeAddressPicUrl',
        src: this.params.takeAddressPicUrl
      }, {
        name: '身份证正面照',
        key: 'idCardPortraitPhotoUrl',
        src: this.params.idCardPortraitPhotoUrl
      }, {
        name: '身份证反面照',
        key: 'idCardNationalEmblemPicUrl',
        src: this.params.idCardNationalEmblemPicUrl
      }]
      // 过滤src为空的元素
      this.uploadImgs = uploadImgs.filter(item => {
        // 筛选出路径不为空的且不是已上传的
        let findIndex = Object.keys(this.uploadedImgs).findIndex(key => item.key === key)
        return item.src && findIndex === -1
      })
      this.uploadTotalCount = this.uploadImgs.length
      this.uploadImg()
    },
    uploadImg() {
      if (this.uploadImgs.length > 0) {
        this.$pt.showLoading({
          title: `图片上传中${this.uploadedCount}/${this.uploadTotalCount}`,
          mask: true
        })
        const uploadTask = this.$pt.uploadFile({
          url: process.env.BASE_API + '/common/uploadFiles',
          filePath: this.uploadImgs[0].src,
          name: 'files',
          success: res => {
            const result = JSON.parse(res.data)
            if (result.code === 101) {
              this.uploadedImgs[this.uploadImgs[0].key] = result.data[0]
              this.uploadImgs.shift()
              this.uploadedCount++
              this.uploadImg()
            } else {
              console.log('图片上传发生错误', result.msg)
              // 调用图片上传出错处理函数
              this.checkError(this.uploadImgs[0])
            }
          },
          fail: err => {
            console.log('上传失败', err, this.uploadImgs[0].key)
            // 调用图片上传出错处理函数
            this.checkError(this.uploadImgs[0])
          }
        })
        uploadTask.onProgressUpdate((res) => {
          console.log('上传进度', res.progress)
        })
      } else {
        // 图片全部上传完，调用申请团长接口
        this.$pt.hideLoading()
        this.saveVillageCommanderApply()
      }
    },
    checkError(curUpload) {
      if (this.uploadErrCount >= 1) {
        this.uploadErrCount = 0
        this.uploadedCount = 0
        this.$pt.hideLoading()
        this.$utils.showToast({
          title: `${curUpload.name}上传出错，请重新选择图片`,
          duration: 3000
        })
        return
      }
      this.uploadErrCount++
      this.uploadImg()
    },
    saveVillageCommanderApply() {
      // 申请团长接口
      let params = {
        enterpriseId: this.appInfo.enterpriseId, // 企业id
        memberId: this.memberId, // 微客id
        isHasStore: this.params.isHasStore, // 是否有无门店：0-否，1-有
        recruiterId: '', // 招募员id
        businessLicensePicUrl: this.uploadedImgs.businessLicensePicUrl, // 营业执照图片地址
        takeTypeId: this.params.takeTypeId, // 提货点类型Id
        takeName: this.params.takeName, // 提货点名称
        takeAddress: this.params.address.address, // 提货点地址
        lat: this.params.address.latitude, // 纬度
        lng: this.params.address.longitude, // 经度
        takeAddressPicUrl: this.uploadedImgs.takeAddressPicUrl, // 提货地址图片地址（门店或小区）
        idCardNationalEmblemPicUrl: this.uploadedImgs.idCardNationalEmblemPicUrl, // 身份证国徽照地址
        idCardPortraitPhotoUrl: this.uploadedImgs.idCardPortraitPhotoUrl, // 身份证人像照地址
        idCardRealName: this.params.idCardRealName, // 身份证真实姓名
        idCardNumber: this.params.idCardNumber, // 身份证号
        applySource: this.storeApply ? 2 : 1 // 申请类型 1：团长申请 2：门店申请
      }
      saveVillageCommanderApply(params).then(response => {
        if (response.isError) return
        if (this.storeApply) {
          // 申请门店
          // 移除申请门店标志
          this.$pt.removeStorageSync('store-apply')
          // 添加已提交申请门店标志
          this.$pt.setStorageSync('store-applied', true)
        } else {
          // 申请团长
          // 移除申请团长标志
          this.$pt.removeStorageSync('leader-apply')
          // 添加已提交申请团长标志
          this.$pt.setStorageSync('leader-applied', true)
        }
        this.$pt.reLaunch({ url: `/pages/home/apply-result/main?memberId=${this.memberId}&phone=${this.phone}` })
      }).catch(() => {
      })
    }
  }
}
</script>
<style lang="less" scoped>
@B5: #B5B5B5;
@selectColor: #FF1717;
.top-step{
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #F5F5F5;
  .B5{
    color: @B5;
  }
  .step-index{
    height: 16px;
    width: 16px;
    font-size: 13px;
    line-height: 16px;
    text-align: center;
    border-radius: 50%;
    background-color: @B5;
    color: #fff;
  }
  .step-active{
    background-color: #FF1717;
  }
}
.footer{
  height: 64px;
  background-color: #fff;
  box-shadow: 0 0 8px rgba(155, 155, 155, 0.26);
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  font-size: 16px;
  font-weight: bold;
  box-sizing: border-box;
  .last-step{
    padding: 0 20px;
    margin-right: 30px;
    height: 48px;
    line-height: 48px;
  }
  .next-step{
    height: 48px;
    flex: 1;
    background-color: #FF243D;
    border-radius: 24px;
    line-height: 48px;
    text-align: center;
    color: #fff;
  }
}
.tip-box{
  width: 274px;
  background-color: #FFF;
  font-size: 18px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  .tip-box--title{
    font-size: 15px;
    font-weight: bold;
    background-color: #FFF2F2;
    height: 45px;
    text-align: center;
    line-height: 45px;
    border-radius: 0 0 50% 50%;
    width: 400px;
    margin-left: -63px;
  }
  .tip-box--content{
    margin-top: 18px;
    padding: 0 25px;
  }
  .tip-box--footer{
    display: flex;
    align-items: center;
    font-size: 16px;
    width: 100%;
    margin-top: 25px;
    .tip-box__cancel,
    .tip-box__confirm{
      height: 44px;
      line-height: 44px;
      text-align: center;
      flex: 1;
    }
    .tip-box__cancel{
      background-color: #F5F5F5;
    }
    .tip-box__confirm{
      color: #FFF;
      background-color: @selectColor;
    }
  }
}
</style>
